import React, { useState, useEffect } from "react";
import {
  Breadcrumb,
  Layout,
  Form,
  Input,
  Button,
  Space,
  Table,
  Drawer,
  Menu,
  Radio,
  Typography,
  Popconfirm,
  InputNumber,
  Row,
  message,
  Col,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import {
  getAuthList,
  getActionList,
} from "../../api/auth/index";
const { Content } = Layout;

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === "number" ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `${title}不能为空！`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

function NewService1() {
  const [auths, setAuths] = useState(auths);
  useEffect(() => {
    setAuths(getAuthList());
  }, []);

  const [actions, setActions] = useState(actions);
  useEffect(() => {
    setActions(getActionList);
  }, []);

  const [form] = Form.useForm();
  const [editingid, setEditingId] = useState("");
  const [mineditingid, setMinEditingId] = useState("");

  const isEditing = (record) => record.id === editingid;
  const isminEditing = (record) => record.action === mineditingid;

  const edit = (record) => {
    form.setFieldsValue({
      id: "",
      name: "",
      status: "",
      ...record,
    });
    setEditingId(record.id);
  };

  const minedit = (record) => {
    form.setFieldsValue({
      action: "",
      name: "",
      describe: "",
      ...record,
    });
    setMinEditingId(record.action);
  };

  const cancel = () => {
    setEditingId("");
  };
  const mincancel = () => {
    setMinEditingId("");
  };

  const save = async (id) => {
    try {
      const row = await form.validateFields();
      const newauths = [...auths];
      const index = newauths.findIndex((item) => id === item.id);

      if (index > -1) {
        const item = newauths[index];
        newauths.splice(index, 1, { ...item, ...row });
        setAuths(newauths);
        setEditingId("");
      } else {
        newauths.push(row);
        setAuths(newauths);
        setEditingId("");
      }
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };

  const minsave = async (action) => {
    try {
      const minrow = await form.validateFields();
      const newactions = [...actions];
      const minindex = newactions.findIndex((i) => action === i.action);

      if (minindex > -1) {
        const i = newactions[minindex];
        newactions.splice(minindex, 1, { ...i, ...minrow });
        setActions(newactions);
        setMinEditingId("");
      } else {
        newactions.push(minrow);
        setActions(newactions);
        setMinEditingId("");
      }
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };

  const handleDelete = (id) => {
    let newauths = auths.filter((item) => item.id !== id);
    setAuths(newauths);
  };

  const minhandleDelete = (action) => {
    let newactions = actions.filter((item) => item.action !== action);
    setActions(newactions);
  };

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      width: "35%",
      editable: true,
    },
    {
      title: "名称",
      dataIndex: "name",
      width: "35%",
      editable: true,
    },
    {
      title: "状态",
      dataIndex: "status",
      width: "15%",
      editable: true,
      render: (status) => {
        if (status === 0) return "禁用";
        return "启用";
      },
    },
    {
      title: "操作",
      dataIndex: "action",
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.id)}
              style={{
                marginRight: 8,
              }}
            >
              保存
            </Typography.Link>
            <Popconfirm title="是否取消" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <span>
            <Typography.Link
              disabled={editingid !== ""}
              onClick={() => edit(record)}
            >
              编辑
            </Typography.Link>
            <Typography.Link style={{ marginLeft: 10 }}>
              <Popconfirm
                title="确定要删除吗？"
                onConfirm={() => handleDelete(record.id)}
              >
                <a>删除</a>
              </Popconfirm>
            </Typography.Link>
          </span>
        );
      },
    },
  ];

  const newclumns = [
    {
      title: "操作类型",
      dataIndex: "action",
      width: "25%",
      editable: true,
    },
    {
      title: "名称",
      dataIndex: "name",
      width: "25%",
      editable: true,
    },
    {
      title: "描述",
      dataIndex: "describe",
      width: "25%",
      editable: true,
    },
    {
      title: "操作",
      dataIndex: "action",
      render: (_, record) => {
        const editable = isminEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => minsave(record.action)}
              style={{
                marginRight: 8,
              }}
            >
              保存
            </Typography.Link>
            <Popconfirm title="是否取消" onConfirm={mincancel}>
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <span>
            <Typography.Link
              disabled={mineditingid !== ""}
              onClick={() => minedit(record)}
            >
              编辑
            </Typography.Link>
            <Typography.Link style={{ marginLeft: 10 }}>
              <Popconfirm
                title="确定要删除吗？"
                onConfirm={() => minhandleDelete(record.action)}
              >
                <a>删除</a>
              </Popconfirm>
            </Typography.Link>
          </span>
        );
      },
    },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === "status" ? "number" : "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  const mincolumns = newclumns.map((cl) => {
    if (!cl.editable) {
      return cl;
    }

    return {
      ...cl,
      onCell: (record) => ({
        record,
        inputType: cl.dataIndex === "action" ? "text" : "text",
        dataIndex: cl.dataIndex,
        title: cl.title,
        editing: isminEditing(record),
      }),
    };
  });

  const onFinish = (values) => {
    console.log(values);
    let newauths = auths.filter(
      (item) => item.id.includes(values.id) || item.name.includes(values.name)
    );
    setAuths(newauths);
  };

  const [visible, setVisible] = useState(false);

  const showDrawer = () => {
    setVisible(true);
  };

  const onClose = () => {
    setVisible(false);
  };

  const onDFinish = (values) => {
    const data = {
      id: values.ID,
      name: values.Name,
      status: values.status,
      actions: [actions],
    };
    const newauths = [...auths];
    newauths.unshift(data);
    console.log(newauths);
    setAuths(newauths);
    message.success("添加成功！");
  };

  return (
    <>
      <Breadcrumb separator=">">
        <Breadcrumb.Item href="/services">角色管理</Breadcrumb.Item>
        <Breadcrumb.Item href="/services/1">权限管理</Breadcrumb.Item>
      </Breadcrumb>

      <Content style={{ margin: "15px 0" }}>
        <Form layout="inline" onFinish={onFinish}>
          <Form.Item name="id" label="ID" style={{ width: 400 }}>
            <Input />
          </Form.Item>
          <Form.Item name="name" label="名称" style={{ width: 400 }}>
            <Input />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button htmlType="reset">重置</Button>
          </Form.Item>
        </Form>
      </Content>
      <Button type="primary" icon={<PlusOutlined />} onClick={showDrawer}>
        新增
      </Button>
      <Drawer
        title="新增权限"
        width={720}
        placement="right"
        onClose={onClose}
        visible={visible}
      >
        <Menu mode="horizontal" defaultSelectedKeys="newCreat">
          <Menu.Item key="newCreat">基本信息</Menu.Item>
        </Menu>
        <Form
          onFinish={onDFinish}
          style={{ position: "absolute", marginTop: 10 }}
        >
          <Row style={{ width: 650 }}>
            <Form.Item
              label="权限标识(ID)"
              name="ID"
              rules={[{ required: true, message: "权限标识(ID)不能为空" }]}
            >
              <Input />
            </Form.Item>
            <Col offset={2}>
              <Form.Item
                label="权限名称"
                name="Name"
                rules={[{ required: true, message: "权限名称不能为空！" }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: "必须选择一个状态" }]}
            style={{ position: "relative", top: 5, left: "35%" }}
          >
            <Radio.Group buttonStyle="solid">
              <Radio.Button value="0">禁用</Radio.Button>
              <Radio.Button value="1">启用</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form form={form} component={false}>
            <Table
              components={{
                body: {
                  cell: EditableCell,
                },
              }}
              dataSource={actions}
              columns={mincolumns}
              rowClassName="editable-row"
              pagination={{
                onChange: cancel,
              }}
              title={() => "操作配置"}
            />
          </Form>
          <Form.Item>
            <Button htmlType="reset">取消</Button>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
      <Form form={form} component={false}>
        <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          dataSource={auths}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={{
            onChange: cancel,
          }}
        />
      </Form>
    </>
  );
}

export default NewService1;
